import * as React from 'react';
import styles from './index.less';
import {
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Breadcrumb,
  Modal,
  Spin,
} from 'antd';
import { connect } from 'umi';
import request from '@/http';
import Edit from '@/components/richEdit';

const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};
export default class UserManager extends React.Component<any, any> {
  constructor(props) {
    super(props);
    this.searchOnClick = this.searchOnClick.bind(this);
    this.pageOnChange = this.pageOnChange.bind(this);
    this.deleteOnClick = this.deleteOnClick.bind(this);
    this.modelOnCancel = this.modelOnCancel.bind(this);
    this.modelOnOk = this.modelOnOk.bind(this);
    this.initUserEditor = this.initUserEditor.bind(this);
    this.state = {
      dataSource: [],
      pagination: {
        current: 1,
        total: 1,
        pageSize: 10,
        showSizeChanger: true,
        pageSizeOptions: ['10', '50', '200', '500'],
      },
      userEditor: {
        isModalVisible: false,
        id: null,
        userNo: null,
        userName: null,
        description: null,
        sex: null,
      },
    };
  }

  formObject = React.createRef<any>();
  formObjectForEdit = React.createRef<any>();

  async loadDataSource(userParams: any, pageValue: any, pageSizeValue: any) {
    const result: any = await request.post('/api/getUserListByPager', {
      ...userParams,
      pageIndex: pageValue - 1,
      pageSize: pageSizeValue,
    });
    if (result.success) {
      const data = result.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        userName: user.userName,
        userNo: user.userNo,
        description: user.description,
        sex: user.sex,
        createTime: user.createTime,
        updateTime: user.updateTime,
      }));
      const newPageObject = {
        ...this.state.pagination,
        current: pageValue,
        pageSize: pageSizeValue,
        total: result.totalCount,
      };
      this.setState({
        dataSource: data,
        pagination: newPageObject,
      });
    }
  }

  componentDidMount(): void {
    this.loadDataSource(null, 1, this.state.pagination.pageSize).finally();
  }

  searchOnClick() {
    this.loadDataSource(
      this.formObject.current.getFieldsValue(),
      1,
      this.state.pagination.pageSize,
    ).finally();
  }

  pageOnChange(page: any) {
    this.loadDataSource(
      this.formObject.current.getFieldsValue(),
      page.current,
      page.pageSize,
    ).finally();
  }

  initUserEditor(isModalVisible, user) {
    if (user) {
      this.setState({
        userEditor: {
          isModalVisible: isModalVisible,
          id: user.id,
          userNo: user.userNo,
          userName: user.userName,
          description: user.description,
          sex: user.sex.code,
        },
      });
    } else {
      this.setState({
        userEditor: {
          isModalVisible: isModalVisible,
          id: null,
        },
      });
    }
  }

  modelOnCancel() {
    this.initUserEditor(false, null);
  }

  async modelOnOk() {
    const data = await this.formObjectForEdit.current.validateFields();
    const result: any = await request.post('/api/addOrUpdateUser', {
      ...data,
      id: this.state.userEditor.id,
    });
    if (result.success) {
      if (this.state.userEditor.id == null) {
        message.success('用户添加成功');
      } else {
        message.success('用户修改成功');
      }
      this.initUserEditor(false, null);
    }
  }

  async deleteOnClick(id) {
    const result: any = await request.get('/api/removeUserById?id=' + id);
    if (result.success) {
      message.success('用户删除成功');
      this.loadDataSource(
        this.formObject.current.getFieldsValue(),
        this.state.pagination.current,
        this.state.pagination.pageSize,
      ).finally();
    }
  }

  render() {
    return (
      <>
        <div className="pageNavigate">
          <Breadcrumb>
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>用户管理</Breadcrumb.Item>
            <Breadcrumb.Item>列表管理</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="pageMain">
          <div className="pageContent">
            <div className={styles.searchForm}>
              <Form layout="inline" ref={this.formObject}>
                <Form.Item label="用户编号" name="userNo">
                  <Input placeholder="请输入用户编号..." />
                </Form.Item>
                <Form.Item label="用户名称" name="userName">
                  <Input placeholder="请输入用户名称..." />
                </Form.Item>
                <Form.Item label="性别" name="sex" initialValue="">
                  <Select>
                    <Option value="">请选择...</Option>
                    <Option value="MALE">男性</Option>
                    <Option value="FEMAL">女性</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="描述" name="description">
                  <Input placeholder="请输入描述..." />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" onClick={this.searchOnClick}>
                    查询
                  </Button>
                </Form.Item>
              </Form>
            </div>
            <div className={styles.mainTable}>
              <Button
                style={{ marginBottom: '10px' }}
                type="primary"
                onClick={() => {
                  this.initUserEditor(true, null);
                }}
              >
                新增
              </Button>
              <Spin spinning={false}>
                <Table
                  scroll={{ x: true }}
                  columns={[
                    {
                      title: '序号',
                      dataIndex: 'id',
                      key: 'id',
                      width: 50,
                    },
                    {
                      title: '用户编号',
                      dataIndex: 'userNo',
                      key: 'userNo',
                      width: 400,
                    },
                    {
                      title: '用户名称',
                      dataIndex: 'userName',
                      key: 'userName',
                      width: 100,
                    },
                    {
                      title: '性别',
                      dataIndex: 'sex',
                      key: 'sex',
                      width: 100,
                      align: 'center',
                      render: (sex) => sex.message,
                    },
                    {
                      title: '描述',
                      dataIndex: 'description',
                      key: 'description',
                      width: 500,
                      render: (description: any) => (
                        <>
                          <div
                            dangerouslySetInnerHTML={{ __html: description }}
                          ></div>
                          <div>{description}</div>
                        </>
                      ),
                    },
                    {
                      title: '创建时间',
                      dataIndex: 'createTime',
                      key: 'createTime',
                      width: 100,
                    },
                    {
                      title: '更新时间',
                      dataIndex: 'updateTime',
                      key: 'updateTime',
                      width: 100,
                    },
                    {
                      title: '操作',
                      key: 'action',
                      align: 'center',
                      width: 100,
                      render: (row: any) => (
                        <>
                          <Button
                            type="link"
                            onClick={() => {
                              this.initUserEditor(true, row);
                            }}
                          >
                            编辑
                          </Button>
                          <Button
                            type="link"
                            onClick={() => {
                              this.deleteOnClick(row.id);
                            }}
                          >
                            删除
                          </Button>
                        </>
                      ),
                    },
                  ]}
                  dataSource={this.state.dataSource}
                  pagination={this.state.pagination}
                  onChange={this.pageOnChange}
                  tableLayout="fixed"
                  bordered
                />
              </Spin>
            </div>
          </div>
        </div>
        <Modal
          width={1000}
          title={this.state.userEditor.id ? '编辑' : '新增'}
          visible={this.state.userEditor.isModalVisible}
          onCancel={this.modelOnCancel}
          onOk={this.modelOnOk}
          maskClosable={false}
          destroyOnClose
          okText="确认"
          cancelText="取消"
        >
          <Form
            {...layout}
            name="editForm"
            initialValues={this.state.userEditor}
            ref={this.formObjectForEdit}
            preserve={false}
            onFinish={(value) => {
              console.log(value);
            }}
          >
            <Form.Item
              label="用户编号"
              name="userNo"
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: '用户编号不能为空!',
                },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
              style={{ marginBottom: 24 }}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="用户名称"
              name="userName"
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: '用户名称不能为空!',
                },
                { max: 30, message: '最大长度不能超过30!' },
              ]}
              style={{ marginBottom: 24 }}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="性别"
              name="sex"
              rules={[{ required: true, message: '性别不能为空!' }]}
              style={{ marginBottom: 24 }}
            >
              <Select>
                <Option value="">请选择</Option>
                <Option value="MALE">男性</Option>
                <Option value="FEMAL">女性</Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="描述"
              name="description"
              rules={[
                { required: true, whitespace: true, message: '描述不能为空!' },
                { max: 2000, message: '最大长度不能超过2000!' },
              ]}
              style={{ marginBottom: 24 }}
            >
              <Edit />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}
